package com.moetube.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.moetube.entity.Result;
import com.moetube.search.dao.ESManagerMapper;
import com.moetube.search.pojo.VideoInfo;
import com.moetube.search.service.ESManagerService;
import com.moetube.video.feign.VideoFeign;
import com.moetube.video.pojo.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private VideoFeign videoFeign;

    /**
     * 创建索引库结构
     */
    @Override
    public void createMappingAndIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(VideoInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(VideoInfo.class);
    }

    /**
     * 导入全部视频数据进入es
     */
    @Override
    public void importAll() {
        List<Video> videoList =videoFeign.findAll().getData();
        if(videoList==null||videoList.size()<=0){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //videoList转换为json
        String jsonVideoList = JSON.toJSONString(videoList);
        //将json转换为videoInfoList
        List<VideoInfo> videoInfoList = JSON.parseArray(jsonVideoList, VideoInfo.class);

        //导入索引库
        esManagerMapper.saveAll(videoInfoList);
    }

    /**
     * 根据videoid查询videoList,再导入索引库
     * @param videoId
     */
    @Override
    public void importDataByVideoId(String videoId) {
        Video video =(Video) videoFeign.findById(videoId).getData();
        if(video==null){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //video转换成json
        String jsonVideo = JSON.toJSONString(video);
        //将json转换为videoInfo
        VideoInfo videoInfo = JSON.parseObject(jsonVideo, VideoInfo.class);

        //导入索引库
        esManagerMapper.save(videoInfo);

    }

    /**
     * 根据videoid删除es索引库中相关的video数据
     * @param videoId
     */
    @Override
    public void delDataByVideoId(String videoId) {
        Video video =(Video) videoFeign.findById(videoId).getData();
        if(video==null){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        esManagerMapper.deleteById(Long.parseLong(video.getId()));
    }
}
